<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/7/20
 * Time: 12:11:44
 */

namespace Service\ActivityService;

use Hyperf\DbConnection\Db;
use Service\MemberService\VipService;
use App\Model\BbcModel\CouponUser;

class CouponStoreService extends \Service\BaseService
{
    /**
     * 查询商品是否有优惠券
     * @param int $cid
     * @param int $mn_sid
     * @param array $goods_ids
     * @param array $mn_user 店铺数据
     * @param int $mid
     * @param array $activityList
     * @return array 返回商品ID所有的优惠券集合
     */
    public function getStoreCoupon(int $cid, int $mn_sid, array $goods_ids ,array $mn_user,int $mid ,array $activityList)
    {
        //判断用户是否是黑卡
        $checkUserIsBlackVipCards       = VipService::instance()->checkUserIsBlackVipCard($mn_user,[$mid]);
        $checkUserIsBlackVipCardsMap    = array_column($checkUserIsBlackVipCards,null,'mid');
        if(!empty($mid)) {
            $isVip = $checkUserIsBlackVipCardsMap[$mid];
        } else {
            $isVip = ['is_vip'=>0,'expire_time'=>0];
        }
        $where = [
            ['ly_coupon.cid','=',$cid],
            ['ly_coupon.status','=',2],
            ['ly_coupon.rule_type','=',1],
            ['ly_coupon.scene','in',[1,2]],
        ];
        if($isVip['is_vip'] == 1){
            $where[] = ['ly_coupon.target_type','in',[1,3]];
        }else{
            $where[] = ['ly_coupon.target_type','in',[1,2]];
        }
        $goodsCoupon = [];
        $coupon_list = Db::table('ly_coupon')
            ->select(explode(',','ly_coupon.id,ly_coupon.type,ly_coupon.type_value,ly_coupon.name,ly_coupon.explain,ly_coupon.addition,ly_coupon.min_amount,ly_coupon.sub_amount,ly_coupon.begindate,ly_coupon.enddate,ly_coupon.is_expiration,ly_coupon.addition'))
            ->join('ly_coupon_store','ly_coupon.id','=','ly_coupon_store.coupon_id')
            ->where($where)
            ->where('total','exp',Db::raw('>get'))
            ->where(function ($query) use($mn_sid){
                $query->where(['ly_coupon_store.mn_sid'=>$mn_sid])
                    ->orWhere(['ly_coupon_store.mn_sid'=>0]);
            })
            ->get()->toArray();
        $coupon_ids = array_column($coupon_list,'id');
        $coupon_new_list = $this->couponIsUser($mn_sid,$mid,$coupon_list); //判断用户是否领取/领取后是否使用
        $returnGoodsList = [];
        foreach ($goods_ids as $key=> $goods_id)
        {
            $activityGoods = $activityList[$goods_id] ?? null;
            if( isset($activityList[$goods_id]) ) {
                $goodsCoupon = $this->goodsCoupons((int)$goods_id,$coupon_new_list,$activityGoods);
                if($goodsCoupon){ //商品有优惠券
                    $returnGoodsList[$goods_id] = $goodsCoupon;
                }else{
                    $returnGoodsList[$goods_id] = [];
                }
            } else {
                $returnGoodsList[$goods_id] = [];
            }

        }
        return $returnGoodsList;
    }

    /**
     * @param int $mn_sid
     * @param int $mid
     * @param array $coupon_list
     */
    public function couponIsUser(int $mn_sid,int $mid,array $coupon_list)
    {
        $coupon_ids = array_column($coupon_list,'id');

        //用户领取过的优惠券
        $coupon_user = CouponUser::instance()
            ->where(['mn_sid'=>$mn_sid,'mid'=>$mid])
            ->where('coupon_id','in',$coupon_ids)
            ->select(explode(',','coupon_id,mid,status'))
            ->get()
            ->toArray();
        if(!empty($coupon_user)){
            $user_coupon_list = array_column($coupon_user,null,'coupon_id');
        }else{
            $user_coupon_list = [];
        }
        foreach ($coupon_list as $k=>$v){
            if(isset($user_coupon_list[$v['id']])){ //用户领取过这个优惠券
                if($user_coupon_list[$v['id']]['status'] == 2){
                    $coupon_list[$k]['has_get'] = 0;
                }else{
                    $coupon_list[$k]['has_get'] = 1;
                }
            }else{
                $coupon_list[$k]['has_get'] = 0;
            }
        }
        return $coupon_list;
    }

    /**
     * 获取商品优惠券
     * @param int $goods_id
     * @param array $coupon_list
     * @param array $activity
     */
    public function goodsCoupons(int $goods_id, array $coupon_list,array $activity)
    {
        $data = [];
        $goodsCoupon = [];
        foreach ($coupon_list as $v)
        {
            /*if( !isset($activity[$goods_id]) ) {
                continue;
            }*/

            if($v['type']==2 && !in_array($goods_id,explode(',',$v['type_value']))){
                //指定商品
                continue;
            }
            if($v['addition']==1 && ((isset($activity[$goods_id]['fullActivity']) && $activity[$goods_id]['fullActivity']) || (isset($activity[$goods_id]['goodsActivity']) && $activity[$goods_id]['goodsActivity']))){
                //不叠加任何活动
                continue;
            }
            if($v['addition']==2 && isset($activity[$goods_id]['goodsActivity']) && $activity[$goods_id]['goodsActivity']){
                //不叠加满减促销
                continue;
            }
            if($v['addition']==3 && isset($activity[$goods_id]['fullActivity']) && $activity[$goods_id]['fullActivity']){
                //不叠加整单促销
                continue;
            }
            if($v['is_expiration']==2){
                $v['begindate'] = date('Y-m-d',$v['begindate']);
                $v['enddate'] = date('Y-m-d',$v['enddate']);
            }
            switch ($v['addition']){
                default;
                case 1:
                    $v['notice']="此券与整单促销、商品满减、特价、拼团、秒杀活动不可叠加使用";
                    break;
                case 2:
                    $v['notice']="此券与商品满减、特价、拼团、秒杀活动不可叠加使用";
                    break;
                case 3:
                    $v['notice']="此券与整单促销、特价、拼团、秒杀活动不可叠加使用";
                    break;
                case 4:
                    $v['notice']="此券与特价、拼团、秒杀活动不可叠加使用";
                    break;
            }
            $goodsCoupon[] = $v;
        }
        $data['listTag']       = null;
        $data['goodsTag']      = null;
        $data['couponList']    = $goodsCoupon;
        $data['getCouponList'] = [];
        if($goodsCoupon){
            $data['listTag'] = ['券'];
            $data['goodsTag']['tagName'] = '领券';
            $content = [];
            foreach ($goodsCoupon as $key => $value){
                $min_amount = $goodsCoupon[$key]['min_amount']=round($value['min_amount'],2);
                $sub_amount = $goodsCoupon[$key]['sub_amount']=round($value['sub_amount'],2);
                if($min_amount == 0){
                    $content[] = "减".$sub_amount;
                }else{
                    $content[] = "满".$min_amount."减".$sub_amount;
                }
                if($value['has_get']==1){
                    $data['getCouponList'][]=$goodsCoupon[$key];
                }
            }
            $data['goodsTag']['tagList']=$content;
        }
        return $data;
    }
}